use std::{
    fs,
    io::{BufRead, BufReader, Write},
    net::{TcpListener, TcpStream},
    sync::{
        mpsc::{self, Receiver},
        Arc, Mutex,
    },
    thread::{self, JoinHandle},
    time::Duration,
};
fn main() {
    let listener = TcpListener::bind("127.0.0.1:8899").unwrap();
    let pool = ThreadPool::new(4);
    for stream in listener.incoming().take(2) {
        let _stream = stream.unwrap();
        pool.execute(|| {
            handle_connection(_stream);
        });
    }
}
pub struct ThreadPool {
    workers: Vec<Worker>,
    sender: Option<mpsc::Sender<Job>>,
}
pub struct Worker {
    id: usize,
    thread: Option<JoinHandle<()>>,
}
type Job = Box<dyn FnOnce() + Send + 'static>;
impl Worker {
    fn new(id: usize, receiver: Arc<Mutex<Receiver<Job>>>) -> Worker {
        let thread = thread::spawn(move || loop {
            let message = receiver.lock().unwrap().recv();
            match message {
                Ok(job) => {
                    println!("worker {id} 获得job 开始执行");
                    job();
                }
                Err(_) => {
                    println!("Worker {id} 断开连接");
                    break;
                }
            }
        });
        Worker {
            id,
            thread: Some(thread),
        }
    }
}
impl ThreadPool {
    fn new(size: usize) -> ThreadPool {
        if size < 1 {
            panic!("线程数量不能小于1");
        }
        let (sender, receiver) = mpsc::channel();
        let mut workers = Vec::with_capacity(size);
        let receiver = Arc::new(Mutex::new(receiver));
        for id in 0..size {
            workers.push(Worker::new(id, Arc::clone(&receiver)))
        }
        ThreadPool {
            workers,
            sender: Some(sender),
        }
    }

    fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
        let job = Box::new(f);
        self.sender.as_ref().unwrap().send(job).unwrap();
    }
}

impl Drop for ThreadPool {
    fn drop(&mut self) {
        drop(self.sender.take());
        for worker in &mut self.workers {
            println!("终结worker {}", worker.id);
            if let Some(thread) = worker.thread.take() {
                thread.join().unwrap()
            }
        }
    }
}

fn handle_connection(mut stream: TcpStream) {
    let buff = BufReader::new(&mut stream);
    let request_line = buff.lines().next().unwrap().unwrap();
    let (status_lin, page) = match &request_line[..] {
        "GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "index.html"),
        "GET /sleep HTTP/1.1" => {
            thread::sleep(Duration::from_secs(5));
            ("HTTP/1.1 200 OK", "index.html")
        }
        _ => ("HTTP/1.1 404 NOT FOUND", "404.html"),
    };

    let body = fs::read_to_string(page).unwrap();
    let len = body.len();
    let response = format!("{status_lin}\r\nContent-Length: {len}\r\n\r\n{body}");
    stream.write_all(response.as_bytes()).unwrap();
}
